package com.tgy.springmvc.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author: tgy
 * @Date: 2020-08-21 16:25
 */
@Component
@Slf4j
public class ShowRequestUrl implements ApplicationListener<ApplicationEvent>, EnvironmentAware {

    private String defaultUrl = "http://127.0.0.1";
    private String url;

    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        if (event instanceof ApplicationStartedEvent){

           log.info(url);
        }
    }

    @Override
    public void setEnvironment(Environment environment) {

        this.url = environment.getProperty("server.url");

        if (Objects.isNull(this.url)){

            StringBuilder stringBuilder = new StringBuilder(defaultUrl);
            stringBuilder.append(":")
                        .append(environment.getProperty("server.port"));
            this.url = stringBuilder.toString();
        }
    }
}
